/* 
 * Cashbox is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import <Cashbox/CBPieChartCell.h>
#import <Cashbox/CBChartItem.h>

@implementation CBPieChartCell

+ (void)initialize {
	[self exposeBinding:@"numberStyle"];
}

- (CBChartNumberStyle)numberStyle {
	return numberStyle;
}

- (void)setNumberStyle:(CBChartNumberStyle)style {
	numberStyle = style;
	[[self controlView] setNeedsDisplay:YES];
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
	[self drawInteriorWithFrame:cellFrame inView:controlView];
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
	NSArray *slices = [self objectValue];
	[[NSColor whiteColor] set];
	[NSBezierPath fillRect:cellFrame];
	
	
	float total = 0;
	CBChartItem *object;
	NSEnumerator *objectEnumerator = [slices objectEnumerator];
	while (object = [objectEnumerator nextObject]) {
		total += [object weight];
	}
	
	if (total) {
		
		[[NSGraphicsContext currentContext] saveGraphicsState];
		[[NSGraphicsContext currentContext] setShouldAntialias:YES];
		
		float radius = cellFrame.size.width > cellFrame.size.height ?
		cellFrame.size.height * 3/8 :
		cellFrame.size.width * 3/8;
		float centerX = cellFrame.origin.x + cellFrame.size.width / 2;
		float centerY = cellFrame.origin.y + cellFrame.size.height / 2;
		NSPoint center = NSMakePoint(centerX, centerY);
		NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
									[NSColor grayColor], NSForegroundColorAttributeName,
									nil];
		
		float lastAngle = 0;
		float start = 90 + [[slices objectAtIndex:0] weight] / total * 360 / 2;
		
		objectEnumerator = [slices objectEnumerator];	
		while (object = [objectEnumerator nextObject]) {
			
			float percent = [object weight] / total;
			float startAngle = start - lastAngle * 360;
			float endAngle = start - (lastAngle + percent) * 360;
			float avgAngle = (startAngle + endAngle) / 2;
			float xMove = cos(avgAngle*3.1415926/180);
			float yMove = sin(avgAngle*3.1415926/180);
			NSPoint lineStart = NSMakePoint(center.x + xMove * radius, center.y + yMove * radius);
			NSPoint lineTurn = NSMakePoint(center.x + xMove * radius * 1.07, center.y + yMove * radius * 1.07);
			NSPoint lineEnd = lineTurn;
			if (lineTurn.x >= center.x) { lineEnd.x += radius / 2; }
			else { lineEnd.x -= radius / 2; }
			
			NSBezierPath *line = [NSBezierPath bezierPath];
			[line moveToPoint:lineStart];
			[line lineToPoint:lineTurn];
			[line lineToPoint:lineEnd];
			
			NSBezierPath *slice = [NSBezierPath bezierPath];
			[slice moveToPoint:center];
			[slice appendBezierPathWithArcWithCenter:center
											  radius:radius
										  startAngle:startAngle
											endAngle:endAngle
										   clockwise:YES];
			
			if ([object label]) {
				[[NSColor grayColor] set];
				[line stroke];
			}
			
			[[object color] set];
			[slice fill];
			
			[[NSColor colorWithDeviceRed:1.0 green:1.0 blue:1.0 alpha:0.30] set];
			[slice stroke];
			
			// draw text
			if ([object label]) {
				NSString *string = [object label];
				if (self.numberStyle == CBWeightNumberStyle) {
					if ([self formatter]) {
						string = [[string stringByAppendingString:@" "] stringByAppendingString:
								  [[self formatter] stringForObjectValue:
								   [NSNumber numberWithFloat:[object weight]]]];
					} else {
						string = [string stringByAppendingFormat:@" %f", [object weight]];
					}
				} else if (self.numberStyle == CBPercentNumberStyle) {
					string = [string stringByAppendingFormat:@" %.2f%%", percent * 100];
				}
				NSPoint textPoint = NSMakePoint(lineEnd.x, lineEnd.y - 8);
				NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:string] autorelease];
				NSTextContainer *textContainer = [[[NSTextContainer alloc]
												   initWithContainerSize: NSMakeSize(FLT_MAX, FLT_MAX)] autorelease];
				NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init] autorelease];
				[layoutManager addTextContainer:textContainer];
				[textStorage addLayoutManager:layoutManager];
				[textStorage addAttributes:attributes range:NSMakeRange(0, [textStorage length])];
				[textContainer setLineFragmentPadding:0.0];
				NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
				if (lineTurn.x >= center.x) {
					textPoint.x -= [layoutManager usedRectForTextContainer:textContainer].size.width;
				}
				[layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:textPoint];
			}
			
			lastAngle += percent;
		}
		[[NSGraphicsContext currentContext] restoreGraphicsState];
		
	} else {
		NSMutableParagraphStyle *style = [[[NSMutableParagraphStyle alloc] init] autorelease];
		[style setAlignment:NSCenterTextAlignment];
		NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
									[NSColor grayColor], NSForegroundColorAttributeName,
									style, NSParagraphStyleAttributeName,
									nil];
		NSRect rect = cellFrame;
		rect.origin.y -= rect.size.height / 2 - [[[[NSLayoutManager alloc] init] autorelease]
												 defaultLineHeightForFont:
												 [NSFont systemFontOfSize:[NSFont systemFontSize]]] / 2;
		[FSLocalizedString(@"No information avaialable", nil) drawInRect:rect withAttributes:attributes];
	}
}

@end
